package com.sinodata.bsm.center.engine.notify;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.sino.uam.entity.UserInfo;
import com.sinodata.bsm.center.service.notify.NotifyService;
import com.sinodata.bsm.center.user.UserUtil;
import com.sinodata.bsm.center.util.spring.SpringContextHolder;
import com.sinodata.bsm.common.constants.NotifyConstants;
import com.sinodata.bsm.common.vo.Notify;
import com.sinodata.notify.center.NotifyMessage;
import com.sinodata.notify.center.NotifyMessageImpl;

/**
 * 
 * <p>
 * Description: 事件通知线程
 * </p>
 *
 * @author liulibo
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-7-11 PM 10:32:44    liulibo        1.0         To create
 * </p>
 *
 * @since 
 * @see
 */
public class NotifyMessenger extends Thread {

    private static final Logger logger = Logger.getLogger(NotifyMessenger.class);

    /**
     * 检查一次需要发送通知的间隔时间：30秒
     * 
     */
    private static long SLEEP_INTERVAL = 30 * 1000L;

    private boolean isInterrupted = false;

    @Autowired
    private static NotifyService notifyService = SpringContextHolder.getBean(NotifyService.class);

    /**
     * 构造方法
     * 
     */
    public NotifyMessenger() {
        super();
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Thread#interrupt()
     */
    @Override
    public void interrupt() {
        this.isInterrupted = true;
        super.interrupt();
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Thread#run()
     */
    @Override
    public void run() {
        List<Notify> notifys = new ArrayList<Notify>();//获取通知集合
        while (true) {
            List<Notify> sendNotifys = new ArrayList<Notify>();
            try {
                if (!this.isInterrupted) {
                    try {
                        Thread.sleep(SLEEP_INTERVAL);
                    } catch (InterruptedException e) {
                        //logger.error("notify send thread error", e);
                    }
                }
                this.isInterrupted = false;
                try {
                    notifys = notifyService.findNotifyForSend();
                } catch (Exception e) {
                    // logger.error("failed to find notify for send", e);
                    continue;
                }

                while (true) {
                    if (notifys == null || notifys.size() == 0 || notifys.get(0).getTime().getTime() > System.currentTimeMillis()) {
                        break;
                    }
                    Notify notify = notifys.remove(0);
                    NotifyMode notifyMode = NotifyModeFactory.getInstance().getNotifyMode(notify.getNotifyMode());
                    if (notifyMode == null) {
                        continue;
                    }
                    //TODO 获取实时指标值
                    //获取用户信息
                    UserInfo user = UserUtil.getInstance().getUserById(notify.getUser());
                    if (user == null) {
                        continue;
                    }
                    String destination = notifyMode.getNotifyDestination(user);
                    String msg = notifyMode.createMsg(notify);
                    if (msg == null) {
                        msg = notify.getMsg();
                    }
                    NotifyMessage message = new NotifyMessageImpl(user.getId(), user.getFullName(), NotifyConstants.SYS_NAME, notify.getNotifyMode(), notify.getMsg(), msg, destination);
                    try {
                        Messenger.getInstance().sendNotify(message);
                        sendNotifys.add(notify);
                    } catch (Exception e) {
                        // logger.error("failed to send notify message", e);
                    }
                }
            } catch (Exception ex) {
                //logger.error("failed to send notify message", ex);
            } finally {
                try {
                    notifyService.batchNotify(sendNotifys);
                } catch (Exception e) {
                    logger.error("failed to send notify message", e);
                }
            }
        }
    }

}